package com.zyf.school.manager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zyf.school.manager.domain.Area;
import com.zyf.school.manager.domain.Tree;
import com.zyf.school.manager.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/area/")
public class AreaController {

    @Autowired
    private AreaService areaService;

    private List<Area> areaList;

    private List<Tree> treeList;

    @RequestMapping("areaNameList")
    @ResponseBody
    //通过区域号码查询校区信息
    public List<Area> queryById(String tel) {
        System.out.println("通过" + tel + "查询数据.........................");
        List<Area> list = areaService.queryByParentTel(tel);
        return list;
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        //只要网页中传来的数据格式为yyyy-MM-dd 就会转化为Date类型
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
                true));
    }

    //区域设置
    @RequestMapping("setting")
    public String setting(HttpServletRequest request,@RequestParam("parentTel") String parentTel){
        areaList = areaService.queryByParentTel(parentTel);
        request.setAttribute("areaList",areaList);
        request.setAttribute("areaTree",JSON.toJSON(areaList));
        return "area/setting";
    }
    //添加区域
    @RequestMapping("add")
    public String add(HttpServletRequest request, Area area){
        // 保存数据
        areaService.save(area);
        areaList = areaService.queryByParentTel(area.getParentId());
        request.setAttribute("areaList",areaList);
        request.setAttribute("areaTree",JSON.toJSON(areaList));
        return "area/setting";
    }
}
